package com.mocoop.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaWebView;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.mocoop.entity.PageInfoEntity;
import com.mocoop.ui.MocoopFragment;
import com.mocoop.util.LogcatHelper;

@SuppressLint("NewApi")
public abstract class MocoopActivity extends CordovaActivity {
	public final static int OFF_NET = 0,ON_NET = 1,WIFI_NET = 2;
	public final static String USER_ID = "currentUserID";
	public final static String USER_INFO = "currentUserInfo";
	public final static String MOCOOP_CONFIG = "mocoopConfig";
	public final static String MOCOOP_FIRST_INSTALL = "mocoopFirstInstall";
	
	private static String BASE_URL = "file:///android_asset/html/";
	
	public static String getBASE_URL() {
		return BASE_URL;
	}

	public static void setBASE_URL(String bASE_URL) {
		BASE_URL = bASE_URL;
	}

	protected static MocoopFragment currentFragment;

	private RequestQueue mQueue;
	private BroadcastReceiver netReceiver;
	
	public String getUserID(){
			SharedPreferences sharedPreferences = getSharedPreferences(
					MOCOOP_CONFIG, 0);
			String userID = sharedPreferences.getString(USER_ID, "");
		return userID;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.init();
		mQueue = Volley.newRequestQueue(this);
		LogcatHelper.getInstance(this).init(this);
	}

	
	public CordovaWebView createdWebView() {
		CordovaWebView webView = makeWebView();
		webView.getView().setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
		webView.getView().requestFocusFromTouch();
		if (!webView.isInitialized()) {
			webView.init(cordovaInterface, pluginEntries, preferences);
		}
		cordovaInterface.onCordovaInit(webView.getPluginManager());

		String volumePref = preferences.getString("DefaultVolumeStream", "");
		if ("media".equals(volumePref.toLowerCase(Locale.ENGLISH))) {
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
		}
		return webView;
	}

	public void ajaxRequest(int method, String url, JSONObject jsonObject, Response.Listener<JSONObject> listener, Response.ErrorListener errorlistener, int initialTimeoutMs) {
		if (initialTimeoutMs == 0) {
			initialTimeoutMs = 30000;
		}
		JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(method, url, jsonObject, listener, errorlistener) {
			@Override
			public Map<String, String> getHeaders() {
				HashMap<String, String> headers = new HashMap<String, String>();
				headers.put("Accept", "*/*");
				headers.put("Content-Type", "application/json; charset=UTF-8");

				return headers;
			}
		};
		jsonRequest.setRetryPolicy(new DefaultRetryPolicy(initialTimeoutMs, 1, 1.0f));
		mQueue.add(jsonRequest);
	}

	public static MocoopFragment getCurrentView() {
		return currentFragment;
	}
	
	public static void setCurrentView(MocoopFragment mocoopFragment) {
		MocoopActivity.currentFragment = mocoopFragment;
	}

	public View.OnClickListener getLeftLayoutEvent() {
		return new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				goBack(null);
			}
		};
	}

	public boolean isNetworkConnected() {

		
		ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		if (mNetworkInfo != null) {
			return mNetworkInfo.isAvailable();
		}

		return true;
	}

	private BroadcastReceiver getNetReceiver() {
		BroadcastReceiver netReceiver = new BroadcastReceiver() {
			private boolean firstNotification = true;

			@Override
			public void onReceive(Context context, Intent intent) {
				if (firstNotification) {
					firstNotification = false;
					return;
				}

				ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

				NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
				NetworkInfo activeInfo = manager.getActiveNetworkInfo();

				if (activeInfo == null) {

				} else {

				}
				if (activeInfo == null) {
					netListener(OFF_NET);
				} else {
					netListener(ON_NET);
					if (wifiInfo.getTypeName().equals(activeInfo.getTypeName())) {
						netListener(WIFI_NET);
					}
				}

			}
		};
		this.netReceiver = netReceiver;
		return netReceiver;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			goBack(null);
			return false;
		} else if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
			onButtonMenu();
			return false;
		}
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		IntentFilter filter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");// 创建IntentFilter对象
		registerReceiver(getNetReceiver(), filter);

	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(netReceiver);
	}

	@Override
	protected void onStart() {
		super.onStart();
		LogcatHelper.getInstance(this).start();
	}

	@Override
	protected void onStop() {
		super.onStop();
		LogcatHelper.getInstance(this).stop();
	}

	protected void dialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

		builder.setTitle("提示");
		builder.setMessage("是否退出程序？");
		builder.setNeutralButton("确认", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
				android.os.Process.killProcess(android.os.Process.myPid());
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();

			}
		});
		builder.create().show();
	}

	public void netListener(int netStatus) {

//		if (netStatus == OFF_NET) {
//			currentFragment.showNetStatusClues();
//		} else {
//			currentFragment.hideNetStatusClues();
//		}
	}

	public abstract void jumpNewPage(PageInfoEntity pageInfoEntity);

	public abstract void goBack(MocoopFragment.MyAnimationCallBack animationCallBack);

	public abstract void showMeRightNow();

	public abstract boolean backToSpecifyPage(String targetURL);

	public abstract void notificationToUI(String js, String noticePages);
	
	public abstract List<MocoopFragment> getHistoryList();

	public abstract void onButtonBack();

	public abstract void onButtonMenu();
	

}
